from django.shortcuts import render
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import GoodsCategory,SKU
from .serializers import GoodsSerializers

# 1.面包屑接口
class CategoryView(APIView):
    def get(self,request,pk):
        cat3 = GoodsCategory.objects.get(id=pk)
        cat2 = cat3.parent
        cat1 = cat2.parent
        data = {
            "cat1": cat1.name,
            "cat2": cat2.name,
            "cat3": cat3.name
        }
        return Response(data)


# 查询的分页器
class GoodsPage(PageNumberPagination):

    page_size_query_param = 'page_size'
    max_page_size = 10


# 2.查询分类下的商品列表
class GoodsListView(ListAPIView):
    # queryset = SKU.objects.filter(ca=pk)
    serializer_class = GoodsSerializers
    # 指定分页器
    pagination_class = GoodsPage
    # 指定排序
    filter_backends = [OrderingFilter]
    ordering_fields=['price','sales','create_time']
    def get_queryset(self):
        pk = self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)
